package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Task;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.commons.compress.archivers.zip.AbstractUnicodeExtraField;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private IServiceItemService serviceItemService;
    @Autowired
    private BpmnInfoServiceImpl bpmnInfoService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private TaskService taskService;




    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }


    @Override
    public void save(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.insert(carPackageAudit);
    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(CarPackageAudit carPackageAudit) {
        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }


    @Override
    public List<CarPackageAudit> list() {
        return carPackageAuditMapper.selectAll();
    }

   

    @Override
    @Transactional
    public void deleteByPrimaryKey(Long id) {
        carPackageAuditMapper.deleteByPrimaryKey(id);
    }

    @Override
    public InputStream getProcessImgAsStream(Long id) {
        //通过id获取审核记录对象的状态
        CarPackageAudit audit = this.get(id);
        String instanceId = audit.getInstanceId();
        List<String> highLightedActivities = null;
        if(CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())){
            //获取流程实例对象
            //如果是处于审核中，需要高亮目前运行的节点
            //通过流程实例id获取到目前活动节点
            highLightedActivities = runtimeService.getActiveActivityIds(instanceId);
        }else{
            //如果是审核拒绝或审核通过，就不需要进行高亮
            highLightedActivities = new ArrayList<>();
        }
        //获取流程定义id,通过id获取BpmnModel对象
        BpmnInfo bpmnInfo = bpmnInfoService.get(audit.getBpmnInfoId());
        BpmnModel bpmnModel = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());
        DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        return generator.generateDiagram(bpmnModel,highLightedActivities,Collections.EMPTY_LIST,"宋体","宋体","宋体");
    }

    @Override
    public void cancelApply(Long id) {
        CarPackageAudit audit = this.get(id);
        if(!CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())){
            throw new BusinessException("只有处于审核中的审核记录才允许撤销");
        }
        //将服务单项的审核状态修改为初始化
        Long serviceItemId = audit.getServiceItemId();
        serviceItemService.changeAuditStatus(serviceItemId, ServiceItem.AUDITSTATUS_INIT);
        //删除流程实例
        runtimeService.deleteProcessInstance(audit.getInstanceId(),"撤销审核");
        //将审核对象的状态修改为已撤销
        carPackageAuditMapper.changeStatus(id,CarPackageAudit.STATUS_CANCEL);
    }

    /**
     * @param "审核记录id"
     * @param "审核状态同意还是拒绝"
     * @param "审核记录备注"
     */
    @Override
    @Transactional
    public void audit(Long id, Integer auditStatus, String info) {
        //进行合理性效验
        CarPackageAudit audit = this.get(id);
        //流程处于审核中才可以进行审核
        if(audit == null || !CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())){
            throw new BusinessException("流程处于审核中才可以进行审核");
        }
        //只有处理人才可以对该审核记录进行审核
        if(!ShiroUtils.getUserId().equals(audit.getAuditorId())){
            throw new BusinessException("只有处理人才可以对该审核记录进行审核");
        }
        String userName = ShiroUtils.getUser().getUserName();
        if(CarPackageAudit.STATUS_PASS.equals(auditStatus)) {
            //同意
            info = "[" + userName + "]同意，审批意见：" + info;
        }else {
            //拒绝
            info = "[" + userName + "]拒绝，审批意见：" + info;
        }
        //将审核意见存储到info信息中
        audit.setInfo(audit.getInfo() + "</br>" + info);
        //让流程往后流转，完成任务前需设置流程变量，是通过还是拒绝
        Task task = taskService.createTaskQuery().processInstanceId(audit.getInstanceId())
                .singleResult();
        taskService.setVariable(task.getId(),"auditStatus",auditStatus);
        //添加审批备注
        taskService.addComment(task.getId(),audit.getInstanceId(),info);
        taskService.complete(task.getId());

        //不管通过还是拒绝都需要审核
        audit.setAuditTime(new Date());

        if(CarPackageAudit.STATUS_PASS.equals(auditStatus)){
            //通过
            //判断是否还有下一个节点
            Task nextTask = taskService.createTaskQuery().processInstanceId(audit.getInstanceId())
                    .singleResult();
            if(nextTask != null){
                //有下一个节点
                audit.setAuditorId(Long.parseLong(nextTask.getAssignee()));
            }else{
                //没有下一个节点了，流程走完了，更改审核对象的状态为审核通过，更改服务单项的状态为审核通过
                audit.setStatus(CarPackageAudit.STATUS_PASS);
                serviceItemService.changeAuditStatus(audit.getServiceItemId(),ServiceItem.AUDITSTATUS_APPROVED);
            }
        }else{
            //拒绝
            //审核对象的状态改为审核拒绝
            audit.setStatus(CarPackageAudit.STATUS_REJECT);
            //服务单项的状态改为初始化
            serviceItemService.changeAuditStatus(audit.getServiceItemId(),ServiceItem.AUDITSTATUS_INIT);
        }
        carPackageAuditMapper.updateByPrimaryKey(audit);
    }
}
